package com.version1_1.dao.implement;

import com.SQLGroup.SQLAccess;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.Statement;
import com.util.httpRequest.HttpRequest;
import com.util.picture.StorePicture;
import com.util.property.Properties;
import com.version1_1.dao.ThirdPart.RongCloud.RongCloudDao;
import com.version1_1.dao.UserDao;
import com.version1_1.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/*不使用sun.misc.BASE64Decoder的原因: 是SUN的专属API，未来可能失效，而且还是不安全的，用java.util.Base64代替*/
//import sun.misc.BASE64Decoder;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RongCloudDao rongCloudDao;

    /*创建log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(UserDaoImpl.class);

    /**
     * @param userId
     * @return
     * @Description: TODO(用户注册后更新邀请码)
     */
    @Override
    public String updateUserInviteCode(int userId) {
        String userInviteCode = "kb" + userId;
        int row = jdbcTemplate.update(SQLAccess.UpdateUserselfInviteCodeVersion1_3, new Object[]{userInviteCode, userId});

        if (row == 1) {
            return userInviteCode;
        } else {
            return "null";
        }
    }

    /**
     * @Description: 根据userId获取用户信息
     */
    @Override
    public User getUserInfo(int userId) {
        return (User) jdbcTemplate.queryForObject(SQLAccess.SelectUserInfoWithId, new Object[]{userId}, new BeanPropertyRowMapper(User.class));
    }

    /**
     * @description: 用户注册
     */
    @Override
    public int userRegister(final String telnumber, final String mail, final String password) {
        Map<String, Object> userTelRegion = HttpRequest.getUserTelRegion(telnumber); // 获取手机号码归属地

        KeyHolder key = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection conn)
                    throws SQLException {

                PreparedStatement preStatement = conn.prepareStatement(
                        SQLAccess.AddAUser, Statement.RETURN_GENERATED_KEYS);
                preStatement.setString(1, mail);
                preStatement.setString(2, telnumber);
                preStatement.setString(3, password);
                preStatement.setTimestamp(4, new Timestamp(new Date().getTime()));
                preStatement.setString(5, (String) userTelRegion.get("province"));
                preStatement.setString(6, (String) userTelRegion.get("city"));
                return preStatement;
            }
        }, key);
        return key.getKey().intValue();
    }

    /**
     * @description: 用户登陆
     */
    @Override
    public Map<String, Object> userLogin(int userId, String mail, String telnumber, String password) {

        /*SQL查询语句*/
        String sqlString = null;
        /*用户信息Map*/
        Map<String, Object> userInfoMap = null;


        /**
         * 逻辑处理部分
         */
        try {
            // 判断用户是否已经有userId,如果有则用userId和userPasswd进行验证否则用userMail和userPasswd进行验证
            if (userId < 0) {
                if (!"".equals(mail) && "".equals(telnumber)) {
                    LOGGER.info("用户登陆,使用邮箱登陆...");
                    userInfoMap = jdbcTemplate.queryForMap(SQLAccess.SelectUserInfoWithMail,
                            new Object[]{mail, password});
                }
                if ("".equals(mail) && !"".equals(telnumber)) {
                    LOGGER.info("用户登陆，使用手机号登陆...");
                    userInfoMap = jdbcTemplate.queryForMap(SQLAccess.SelectUserInfoWithTel,
                            new Object[]{telnumber, password});
                }
                if (!"".equals(mail) && !"".equals(telnumber)) {
                    //调用方法错误，邮箱和手机号都有
                    LOGGER.error("用户登陆，手机号和邮箱号都存在，错误...");
                    return userInfoMap;
                }

            } else {
                userInfoMap = jdbcTemplate.queryForMap(SQLAccess.SelectUserInfoWithIdAndPasswd, new Object[]{
                        userId, password});
            }
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.info("用户登陆，找不到用户信息(" + "userId: " + userId + ",mail: " + mail + "telnumber: " + telnumber + ",password: " + password + ")...");
            return userInfoMap; //使用 return userInfoMap代替return null
        }

        String collectString = getCollectString(userId, mail, telnumber);
        userInfoMap.put("userCollect", collectString);

        return userInfoMap;

    }

    /**
     * @description: 更新用户个人信息
     * TODO: 更新用户个人信息服务器端响应太慢,2016.01.10
     */
    @Override
    public boolean updateUserInfo(int userId, String userName,
                                  String userPhoto, String userSex, String school, int schoolYear) {
        String updateString = "";
        int updateResult = 0;

        User user = getUserInfo(userId);

        if (!("".equals(userName))) {
            if (!("".equals(userPhoto))) {
                if (!("".equals(userSex))) {
                    // userName,userPhoto,userSex: 1,1,1
                    LOGGER.info("更新用户个人信息，更新内容：昵称、头像、性别");

                    try {
                    /*将String格式的图片数据转换为图片存储到服务器*/
                        String photoPath = StorePicture.store(user.getUserPhoto(), userPhoto, Properties.UserPhoto_Tag);

                        //rongCloudDao.refreshUser(userId, userName, photoPath);

                        updateResult = jdbcTemplate.update(SQLAccess.UpdateUserNamePhotoSex,
                                new Object[]{userName, photoPath, userSex, userId});
                    } catch (Exception exception) {
                        LOGGER.error("更新用户个人信息失败,更新内容: 昵称,头像,性别,userName: " + userName + ", userSex: " + userSex, exception);
                    }
                } else {
                    // userName,userPhoto,userSex: 1,1,0
                    LOGGER.info("更新用户个人信息，更新内容：昵称、头像");

                    try {
                    /*将String格式的图片数据转换为图片存储到服务器*/
                        String photoPath = StorePicture.store(user.getUserPhoto(), userPhoto, Properties.UserPhoto_Tag);

                        updateResult = jdbcTemplate.update(SQLAccess.UpdateUserNamePhoto,
                                new Object[]{userName, photoPath, userId});

                        rongCloudDao.refreshUser(userId, userName, photoPath);
                    } catch (Exception exception) {
                        LOGGER.error("更新用户个人信息失败,更新内容: userName: " + userName + ", userPhoto: " + userPhoto, exception);
                    }
                }
            } else {
                if (!("".equals(userSex))) {
                    // userName,userPhoto,userSex: 1,0,1
                    LOGGER.info("更新用户个人信息，更新内容：昵称、性别");
                    updateResult = jdbcTemplate.update(SQLAccess.UpdateUserNameSex,
                            new Object[]{userName, userSex, userId});

                    rongCloudDao.refreshUser(userId, userName, null);
                } else {
                    // userName,userPhoto,userSex: 1,0,0
                    LOGGER.info("更新用户个人信息，更新内容：昵称");
                    updateResult = jdbcTemplate.update(SQLAccess.UpdateUserName,
                            new Object[]{userName, userId});

                    rongCloudDao.refreshUser(userId, userName, null);
                }
            }
        } else {
            if (!("".equals(userPhoto))) {
                if (!("".equals(userSex))) {
                    // userName,userPhoto,userSex: 0,1,1
                    LOGGER.info("更新用户个人信息，更新内容：头像、性别");

                    try {
                    /*将String格式的图片数据转换为图片存储到服务器*/
                        String photoPath = StorePicture.store(user.getUserPhoto(), userPhoto, Properties.UserPhoto_Tag);

                        updateResult = jdbcTemplate.update(SQLAccess.UpdateUserPhotoSex,
                                new Object[]{photoPath, userSex, userId});

                        rongCloudDao.refreshUser(userId, null, photoPath);
                    } catch (Exception exception) {
                        LOGGER.error("更新用户个人信息失败,更新内容:头像,性别,userPhoto: " + userPhoto + ", userSex: " + userSex, exception);
                    }
                } else {
                    // userName,userPhoto,userSex: 0,1,0
                    LOGGER.info("更新用户个人信息，更新内容：头像");

                    try {
                    /*将String格式的图片数据转换为图片存储到服务器*/
                        String photoPath = StorePicture.store(user.getUserPhoto(), userPhoto, Properties.UserPhoto_Tag);

                        updateResult = jdbcTemplate.update(SQLAccess.UpdateUserPhoto,
                                new Object[]{photoPath, userId});

                        rongCloudDao.refreshUser(userId, null, photoPath);
                    } catch (Exception exception) {
                        LOGGER.error("更新用户个人信息失败,更新内容: 头像,userPhoto: " + userPhoto, exception);
                    }
                }
            } else {
                if (!("".equals(userSex))) {
                    // userName,userPhoto,userSex: 0,0,1
                    LOGGER.info("更新用户个人信息，更新内容：性别");
                    updateResult = jdbcTemplate.update(SQLAccess.UpdateUserSex,
                            new Object[]{userSex, userId});
                } else {
                    // userName,userPhoto,userSex: 0,0,0
                    LOGGER.info("更新用户个人信息，更新内容：无");
                }
            }
        }

        /**
         * 如果更新的内容包括学校、入学年份
         */
        if (!"".equals(school)) {
            if (schoolYear != -1) {
                updateResult = jdbcTemplate.update(SQLAccess.UpdateUserSchoolYear, new Object[]{school, schoolYear, userId});
            } else {
                updateResult = jdbcTemplate.update(SQLAccess.UpdateUserSchool, new Object[]{school, userId});
            }
        } else {
            if (schoolYear != -1) {
                updateResult = jdbcTemplate.update(SQLAccess.UpdateUserYear, new Object[]{schoolYear, userId});
            }
        }

        return updateResult != 0 ? true : false;
    }

    /**
     * 根据第三方平台获取的信息更新用户信息(头像,性别,昵称)
     *
     * @param userId
     * @param userName
     * @param userPhoto
     * @param userSex
     * @return
     */
    @Override
    public boolean updateUserInfo(int userId, String userName, String userPhoto, String userSex) {

        if (userName == null) {
            LOGGER.error("获取第三方平台用户信息失败,userId: " + userId);
            userName = "";
        }

        if (userPhoto == null) {
            userPhoto = "";
        }

        if (userSex == null) {
            userSex = "男";
        }

        String sql = "UPDATE user_info SET userName=?,userPhoto=?,userSex=? WHERE userId=?";
        int row = jdbcTemplate.update(sql, new Object[]{userName, userPhoto, userSex, userId});

        return (row == 1) ? true : false;
    }

    /**
     * @description: 更新用户关注列表
     */
    @Override
    public boolean updateFocusList(String updateListString) {
        JSONObject updateJsonObject = JSONObject.parseObject(updateListString);

        int userId = updateJsonObject.getIntValue("userId");
        JSONArray updateJsonArray = updateJsonObject
                .getJSONArray("updateFocusList");

        //获取用户现有关注列表
        String userFocusListString = "";

        try {
            userFocusListString = jdbcTemplate.queryForObject(SQLAccess.SelectUserFocusInfo,
                    String.class, new Object[]{userId});
        } catch (EmptyResultDataAccessException exception) {
            //获取错误
            LOGGER.error("更新用户关注列表,获取用户现有关注列表失败...", exception);
            return false;
        }

        JSONObject userJsonObject = JSONObject.parseObject(userFocusListString);
        JSONArray userJsonArray = userJsonObject.getJSONArray("focusList");


        /*在更新用户关注内容时，同时改变分类关注数量*/
        changeThirdFocusNum(updateJsonArray, userJsonArray);

        //循环更新用户关注内容
        for (int i = 0; i < updateJsonArray.size(); i++) {
            JSONObject updateJson = updateJsonArray.getJSONObject(i);
            int itemNumber = updateJson.getIntValue("itemNumber");
            for (int j = 0; j < userJsonArray.size(); j++) {
                JSONObject userJson = userJsonArray.getJSONObject(j);
                if (userJson.getIntValue("itemNumber") == itemNumber) {
                    userJsonArray.set(j, updateJson);
                }
            }
        }

        //更新用户关注数据库数据
        int result = jdbcTemplate.update(SQLAccess.UpdateUserFocusInfo,
                new Object[]{userJsonObject.toString()});
        boolean updateResult = (result > 0 ? true : false);


        return updateResult;
    }


    /**
     * @description: 获取用户评论的回复消息列表
     */
    @SuppressWarnings("deprecation")
    @Override
    public List getReplyList(int userId, int pageNumber, int pageSize) {

        List replyList = null;

        int count = 0;
        // EmptyResultDataAccessException错误捕获
        try {
            count = jdbcTemplate
                    .queryForInt(SQLAccess.SelectCommentReplyCount, new Object[]{userId});
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("获取用户评论的回复消息列表,获取用户回复列表长度失败,EmptyResultDataAccessException...", exception);
            return replyList;
        }

        //请求分页数大于总页数
        if ((pageNumber - 1) * pageSize >= count) {
            LOGGER.info("获取用户评论的回复消息列表,用户请求分页数大于总页数...");
            return replyList;
        }

        replyList = jdbcTemplate.queryForList(SQLAccess.SelectUserReplyMessage, new Object[]{userId,
                (pageNumber - 1) * pageSize, pageSize});


        removeReplyTag(userId);
        return replyList;
    }


    /**
     * @description: 更改密码
     */
    @Override
    public boolean updatePasswd(int userId, String newPasswd) {
        //新密码为空，返回错误
        if ("".equals(newPasswd)) {
            LOGGER.error("更改密码，json String新密码为空...");
            return false;
        }

        int updateResult = 0;
        // 用户名密码匹配
        updateResult = jdbcTemplate.update(SQLAccess.UpdateUserPasswd, new Object[]{
                newPasswd, userId});
        return updateResult > 0 ? true : false;

    }


    /**
     * @description: 获取用户点赞列表信息
     */
    @SuppressWarnings("deprecation")
    @Override
    public List getPraiseList(int userId, int pageNumber, int pageSize) {

        // 将用户有点赞消息取消
        int updateResult = jdbcTemplate.update(SQLAccess.UpdateAbordCommentPraise, new Object[]{userId});

        if (updateResult == 0) {
            LOGGER.info("去除用户点赞消息，没有记录被更新...");
        }

        List replyList = null;

        int count = 0;

        //EmptyResultDataAccessException错误捕获
        try {
            count = jdbcTemplate
                    .queryForInt(SQLAccess.SelectUserCommentPraiseNumber, new Object[]{userId});
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("获取用户点赞列表信息,获取用户点赞列表条目数错误,EmptyResultDataAccessException...", exception);
            return replyList;
        }

        //请求分页数大于总页数
        if ((pageNumber - 1) * pageSize >= count) {
            LOGGER.info("获取用户点赞列表信息,用户请求分页数大于总页数...");
            return replyList;
        }

        return jdbcTemplate.queryForList(SQLAccess.SelectUserPraiseMessage, new Object[]{userId,
                (pageNumber - 1) * pageSize, pageSize});
    }


    /**
     * @description: 用户反馈
     */
    @Override
    public boolean feedback(int userId, String feedbackType,
                            String feedbackDate, String feedbackContent, String screenShot1, String screenShot2, String screenShot3, String screenShot4) {

        /*字符串转图片的解码类*/
        Base64.Decoder base64Decoder = Base64.getDecoder();
        /*缓冲字节数组*/
        byte[] imageByteArray = null;

        /*反馈图片存储路径*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        String feedbackImagePath = "/kuibu/static/res/feedback/" + simpleDateFormat.format(new Date());

        /**
         * 在Windows平台进行测试时，使用下面的测试地址
         */
        //String feedbackImagePath = "E://"+simpleDateFormat.format(new Date());

        /*四个图片的存储位置*/
        String screenShot1Path = "";
        String screenShot2Path = "";
        String screenShot3Path = "";
        String screenShot4Path = "";

        /*检查screenShot1是否为空*/
        if (screenShot1 == null || "".equals(screenShot1)) {
            LOGGER.info("用户反馈,第一张截图内容为空...");
            screenShot1 = null;
        } else {
            /*base64解码*/
            try {
                imageByteArray = base64Decoder.decode(screenShot1);
            } catch (Exception exception) {
                LOGGER.error("用户反馈,String转字节数组错误...", exception);
                return false;
            }

            /*存储图片*/
            String imageFilePath = new Date().getTime() + "+1.jpg";
            screenShot1Path = imageFilePath;
            File feedBackImage = new File(feedbackImagePath);
            try {
                /*如果路径不存在，则创建路径*/
                if (!feedBackImage.exists()) {
                    feedBackImage.mkdirs();
                }
                File file = new File(feedbackImagePath, imageFilePath);
                OutputStream outputStream = new FileOutputStream(file);
                outputStream.write(imageByteArray);
                outputStream.flush();
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("用户反馈,存储图片错误...", exception);
                return false;
            }

        }

        /*检查screenShot2是否为空*/
        if (screenShot2 == null || "".equals(screenShot2)) {
            LOGGER.info("用户反馈,第二张截图内容为空...");
            screenShot2 = null;
        } else {
            /*base64解码*/
            try {
                imageByteArray = base64Decoder.decode(screenShot2);
            } catch (Exception exception) {
                LOGGER.error("用户反馈,String转字节数组错误...", exception);
                return false;
            }

            /*存储图片*/
            String imageFilePath = feedbackImagePath + new Date().getTime() + "+2.jpg";
            screenShot2Path = imageFilePath;
            try {
                OutputStream outputStream = new FileOutputStream(imageFilePath);
                outputStream.write(imageByteArray);
                outputStream.flush();
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("用户反馈,存储图片错误...", exception);
                return false;
            }

        }

        /*检查screenShot3是否为空*/
        if (screenShot3 == null || "".equals(screenShot3)) {
            LOGGER.info("用户反馈,第三张截图内容为空...");
            screenShot3 = null;
        } else {
            /*base64解码*/
            try {
                imageByteArray = base64Decoder.decode(screenShot3);
            } catch (Exception exception) {
                LOGGER.error("用户反馈,String转字节数组错误...", exception);
                return false;
            }

            /*存储图片*/
            String imageFilePath = feedbackImagePath + new Date().getTime() + "+3.jpg";
            screenShot3Path = imageFilePath;
            try {
                OutputStream outputStream = new FileOutputStream(imageFilePath);
                outputStream.write(imageByteArray);
                outputStream.flush();
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("用户反馈,存储图片错误...", exception);
                return false;
            }

        }

        /*检查screenShot4是否为空*/
        if (screenShot4 == null || "".equals(screenShot4)) {
            LOGGER.info("用户反馈,第四张截图内容为空...");
            screenShot4 = null;
        } else {
            /*base64解码*/
            try {
                imageByteArray = base64Decoder.decode(screenShot4);
            } catch (Exception exception) {
                LOGGER.error("用户反馈,String转字节数组错误...", exception);
                return false;
            }

            /*存储图片*/
            String imageFilePath = feedbackImagePath + new Date().getTime() + "+4.jpg";
            screenShot4Path = imageFilePath;
            try {
                OutputStream outputStream = new FileOutputStream(imageFilePath);
                outputStream.write(imageByteArray);
                outputStream.flush();
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("用户反馈,存储图片错误...", exception);
                return false;
            }

        }

        int feedbackResult = 0;
        feedbackResult = jdbcTemplate.update(SQLAccess.AddAFeedbackInfo, new Object[]{userId,
                feedbackDate, feedbackType, feedbackContent, screenShot1Path, screenShot2Path, screenShot3Path, screenShot4Path});

        //反馈记录失败
        if (feedbackResult == 0) {
            LOGGER.error("用户反馈,反馈记录失败...");
            return false;
        } else {
            return true;
        }

    }


    /**
     * @description: 记录、删除用户单次收藏
     */
    @Override
    public boolean doCollect(int userId, int pageId, int actionType) {
        int doCollectResult = 0;
        if (actionType == 1) {
            LOGGER.info("记录用户单次收藏...");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy.MM.dd");
            doCollectResult = jdbcTemplate.update(SQLAccess.AddAColleckInfo, new Object[]{userId,
                    pageId, simpleDateFormat.format(new Date())});
        } else if (actionType == 0) {
            LOGGER.info("删除用户单次收藏...");
            doCollectResult = jdbcTemplate.update(SQLAccess.DeleteAColleckInfo, new Object[]{userId,
                    pageId});
        } else {
            LOGGER.error("记录删除用户单次收藏,actionType错误(非1也非0)...");
            return false;
        }

        //记录或删除收藏失败
        if (doCollectResult == 0) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * @description: 获取用户收藏列表
     */
    @Override
    public List getCollectList(int userId, int pageNumber) {

        List collectList = null;

        int count = 0;
        // EmptyResultDataAccessException错误捕获
        try {
            count = jdbcTemplate
                    .queryForObject(SQLAccess.SelectUserColleckCount, new Object[]{userId}, Integer.class);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("获取用户收藏列表,获取用户收藏列表长度失败,EmptyResultDataAccessException...", exception);
            return collectList;
        }

        //请求分页数大于总页数
        if ((pageNumber - 1) * Properties.PageSize_Collect >= count) {
            LOGGER.info("获取用户收藏列表,用户请求分页数大于总页数...");
            return collectList;
        }

        return jdbcTemplate
                .queryForList(SQLAccess.SelectUserColleckList, new Object[]{userId, (pageNumber - 1) * Properties.PageSize_Collect, Properties.PageSize_Collect});
    }

    /**
     * @Description: (根据二级分类ID获取用户收藏中特定的二级分类的文章)
     */
    @Override
    public List getSecondCollectList(int userId, int secondType, int pageNumber) {
        List secondCollectList = null;

        int count = 0;
        // EmptyResultDataAccessException错误捕获
        try {
            count = jdbcTemplate
                    .queryForObject(SQLAccess.SelectUserColleckCountOfSecondType, new Object[]{userId, secondType}, Integer.class);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("根据二级分类ID获取用户收藏中特定的二级分类的文章失败,EmptyResultDataAccessException...", exception);
            return secondCollectList;
        }

        //请求分页数大于总页数
        if ((pageNumber - 1) * Properties.PageSize_Collect >= count) {
            LOGGER.error("获取用户收藏列表,用户请求分页数大于总页数...");
            return secondCollectList;
        }

        return jdbcTemplate
                .queryForList(SQLAccess.SelectUserCollerckListOfSecondType, new Object[]{userId, secondType, (pageNumber - 1) * Properties.PageSize_Collect, Properties.PageSize_Collect});
    }

    /**
     * @Description: 获取用户收藏列表信息总的数据
     */
    @Override
    public List getCollectList(int userId) {

        /*获取用户收藏列表数据，总的数据*/
        List collectList = jdbcTemplate
                .queryForList(SQLAccess.SelectAllUserColleckInfo, new Object[]{userId});
        return collectList;
    }


    /**
     * @description: 登陆用户批量删除收藏
     */
    @Override
    public boolean delCollect(int userId, String deleteList) {
        int delCollectResult;
        String sql = "DELETE FROM user_collect WHERE userId=? AND collectId IN (" + deleteList + ")";

        delCollectResult = jdbcTemplate.update(sql, new Object[]{userId});
        //删除收藏失败
        if (delCollectResult == 0) {
            LOGGER.error("登陆用户批量删除用户收藏失败...");
            return false;
        } else {
            return true;
        }
    }


    /**
     * @description: 获取用户收藏字符串
     */
    @Override
    public String getCollectString(int userId, String mail, String telnumber) {

        String sql = "";
        List collectList = null;
        String collectString = "";

        /**
         * 逻辑处理部分
         */
        if (userId < 0) {
            if ("".equals(mail) && !("".equals(telnumber))) {
                LOGGER.info("获取用户收藏字符串,用户以手机号登陆...");
                collectList = jdbcTemplate.queryForList(SQLAccess.SelectUserColleckPageIdsWithTelLogin, new Object[]{telnumber});

            } else if (!("".equals(mail)) && "".equals(telnumber)) {
                LOGGER.info("获取用户收藏字符串,用户以邮箱号登陆...");
                collectList = jdbcTemplate.queryForList(SQLAccess.SelectUserColleckPageIdsWithMailLogin,
                        new Object[]{mail});
            } else if (!("".equals(mail)) && !("".equals(telnumber))) {
                LOGGER.info("获取用户收藏字符串,用户以手机号&邮箱号登陆...");
                collectList = jdbcTemplate.queryForList(SQLAccess.SelectUserColleckPageIdsWithMailAndTelLogin,
                        new Object[]{mail, telnumber});
            } else {
                LOGGER.error("获取用户收藏字符串,未知错误...");
                return null;
            }

        } else {
            collectList = jdbcTemplate.queryForList(SQLAccess.SelectUserColleckPageIdsWithUserId, new Object[]{userId});

        }

        for (int i = 0; i < collectList.size(); i++) {
            Map idMap = (Map) collectList.get(i);
            int id = (int) idMap.get("pageId");
            collectString = collectString.concat(id + ",");
        }

        if (collectString.length() >= 1) {
            collectString = collectString.substring(0,
                    collectString.length() - 1);
        }

        return collectString;
    }


    /**
     * @description: 检测用户是否存在
     */
    @Override
    public boolean checkUserExist(String mail, String telnumber) {
        String sqlString = "";

        /*如果注册使用的是邮箱号*/
        if (!("".equals(mail)) && "".equals(telnumber)) {
            try {
                jdbcTemplate.queryForObject(SQLAccess.SelectIsUserExistWithMail, new Object[]{mail}, Integer.class);
                return true;
            } catch (EmptyResultDataAccessException exception) {
                LOGGER.error("检测用户是否存在,用户不存在,找不到邮箱号...", exception);
                return false;
            }
        }

        /*如果注册使用的是手机号*/
        if (!("".equals(telnumber)) && "".equals(mail)) {
            try {
                int userId = jdbcTemplate.queryForObject(SQLAccess.SelectIsUserExistWithTel, new Object[]{telnumber}, Integer.class);
                return true;
            } catch (EmptyResultDataAccessException exception) {
                LOGGER.info("检测用户是否存在,用户不存在,找不到手机号: " + telnumber);
                return false;
            }
        }
        return false;
    }

    /**
     * @description: 检测用户是否有新消息
     */
    @Override
    public String checkMessage(int userId) {
        boolean hasPraise = false;
        boolean hasSysMessage = false;
        boolean hasReply = false;
        String sql = "";
        String result = "";

        if (!jdbcTemplate.queryForList(SQLAccess.SelectUserIsHasCommentPraiseMessage, new Object[]{userId}).isEmpty()) {
            hasPraise = true;
        }

        if (!jdbcTemplate.queryForList(SQLAccess.SelectUserIsHasCommentReplyMessage, new Object[]{userId}).isEmpty()) {
            hasReply = true;
        }

        if (!jdbcTemplate.queryForList(SQLAccess.SelectUserIsHasSystemMessage, new Object[]{userId}).isEmpty()) {
            hasSysMessage = true;
        }

        if (hasPraise || hasReply || hasSysMessage) {
            result = "true,\"hasPraise\":" + hasPraise + ",\"hasReply\":" + hasReply + ",\"hasSysMessage\":" + hasSysMessage + "";
        } else {
            result = "false";
        }

        return result;

    }

    /**
     * @description: 去除回复标志
     */
    @Override
    public boolean removeReplyTag(int receiverId) {
        try {
            jdbcTemplate.update(SQLAccess.UpdateUserReplyTagRemove, new Object[]{receiverId});
        } catch (Exception exception) {
            LOGGER.error("去除回复标志错误...", exception);
            return false;
        }
        return true;
    }


    /**
     * @description: 获取系统消息
     */
    @Override
    public List getSystemMessageList(int userId) {
        List sysMessageList = jdbcTemplate.queryForList(SQLAccess.SelectSystemMessage, new Object[]{userId});
        return sysMessageList;
    }

    /**
     * @description: 根据三级分类名称得到三级分类所属二级分类ID
     * @warning: 此方法存在漏洞，不可以在SQL语句中拼接参数
     */

    public String getSecondIdByThirdName(String thirdTypeName) {
        int secondType;
        try {
            String sql = "SELECT secondType FROM type_info WHERE thirdTypeName=" + "'" + thirdTypeName + "'";
            secondType = jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("根据三级分类名称找不到对应二级分类名称,thirdTypeName:" + thirdTypeName, exception);
            return null;
        }
        return "" + secondType;
    }


    /**
     * 根据secondType和thirdName获取分类ID
     *
     * @param jsonObject
     * @return
     */
    public int getTypeIdByTypeAndName(JSONObject jsonObject) {
        try {
            int secondType = jsonObject.getIntValue("secondType");
            String thirdName = jsonObject.getString("thirdName");
            String sql = "SELECT thirdTypeId FROM type_info WHERE secondType=? AND thirdTypeName=?";
            int thirdTypeId = jdbcTemplate.queryForObject(sql, new Object[]{secondType, thirdName}, java.lang.Integer.class);
            return thirdTypeId;
        } catch (Exception exception) {
            LOGGER.error("根据secondType和thirdName查找分类ID", exception);
            return -1;
        }

    }


    /**
     * @description: 用户关注信息更改的同时更改三级分类的订阅数
     */
    @Override
    public boolean changeThirdFocusNum(JSONArray updateJsonArray, JSONArray userJsonArray) {

        List<Integer> addFocusNumberList = new ArrayList<>(); // 需要增加订阅量的分类
        List<Integer> minusFocusNumberList = new ArrayList<>(); // 需要减少订阅量的分类

        // 格式:[{"itemNumber":,"focus":[{"secondType":,"thirdName":""}...]}...]
        for (int i = 0; i < updateJsonArray.size(); i++) {
            JSONObject itemObject = updateJsonArray.getJSONObject(i);
            JSONArray itemFocusJsonArray = itemObject.getJSONArray("focus");
            for (int j = 0; j < itemFocusJsonArray.size(); j++) {
                JSONObject thirdTypeJsonObject = itemFocusJsonArray.getJSONObject(j);
                if (!userJsonArray.toJSONString().contains(thirdTypeJsonObject.getString("thirdName"))) {
                    // 如果用户原本关注分类中没有更新的分类 - 分类的订阅量加1
                    addFocusNumberList.add(getTypeIdByTypeAndName(thirdTypeJsonObject));
                }
            }
        }


        for (int i = 0; i < userJsonArray.size(); i++) {
            JSONObject userItemObject = userJsonArray.getJSONObject(i);
            JSONArray userItemFocusJsonArray = userItemObject.getJSONArray("focus");
            for (int j = 0; j < userItemFocusJsonArray.size(); j++) {
                JSONObject userThirdTypeJsonObject = userItemFocusJsonArray.getJSONObject(j);
                if (!updateJsonArray.toJSONString().contains(userThirdTypeJsonObject.getString("thirdName"))) {
                    // 如果更新分类中没有用户原本关注分类 - 分类订阅量减1
                    minusFocusNumberList.add(getTypeIdByTypeAndName(userThirdTypeJsonObject));
                }
            }
        }

        String addTypeIdStr = "";
        for (int typeId : addFocusNumberList) {
            addTypeIdStr = addTypeIdStr.concat(typeId + ",");
        }

        String sql = "";
        if (!addTypeIdStr.isEmpty()) {
            sql = "UPDATE type_info SET collectedNumber=collectedNumber+1 WHERE thirdTypeId IN(" + addTypeIdStr.substring(0, addTypeIdStr.length() - 1) + ")";
            jdbcTemplate.update(sql);
        }


        String minusTypeIdStr = "";
        for (int typeId : minusFocusNumberList) {
            minusTypeIdStr = minusTypeIdStr.concat(typeId + ",");
        }

        if (!minusTypeIdStr.isEmpty()) {
            sql = "UPDATE type_info SET collectedNumber=collectedNumber-1 WHERE thirdTypeId IN(" + minusTypeIdStr.substring(0, minusTypeIdStr.length() - 1) + ")";
            jdbcTemplate.update(sql);
        }


        return true;
    }

    /**
     * 检测用户输入的手机号或者邮箱号是否已经被注册
     */
    @Override
    public boolean checkRegister(String registerInfo, int flag) {
        boolean checkResult = true;
        String sqlStr = "";

        if (flag == 0) {
            // 传入的是手机号
            sqlStr = "SELECT userId FROM user_info WHERE userTel=?";
        } else {
            // 传入的是邮箱号
            sqlStr = "SELECT userId FROM user_info WHERE userMail=?";
        }
        try {
            jdbcTemplate.queryForObject(sqlStr, new Object[]{registerInfo}, Integer.class);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.info("用户的手机号未被注册过");
            checkResult = false;
        }
        return checkResult;
    }

    /**
     * 忘记密码
     */
    @Override
    public boolean forgetPass(String telnumber, String newPassword) {

        try {
            jdbcTemplate.update(SQLAccess.UpdateUserPasswdWithTel, new Object[]{newPassword, telnumber});
        } catch (Exception exception) {
            LOGGER.error("忘记密码，根据telnumber更新密码出错");
            return false;
        }

        return true;
    }

    /**
     * 更新用户融云的token值
     */
    @Override
    public boolean updateUserTokenRY(int userId, String tokenRY) {


        int rows = jdbcTemplate.update(SQLAccess.UpdateRongYunToken, new Object[]{tokenRY, userId});
        if (rows == 0) {
            LOGGER.error("更新用户融云token出错...");
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean updateUserBaiduId(String baiduId, int userid) {
        String sql = "UPDATE user_info SET baiduId=? WHERE userId=?";
        int row = jdbcTemplate.update(sql, new Object[]{baiduId, userid});
        return (row == 1) ? true : false;
    }


}
